package com.nchu.commondevelopmentframework.common.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nchu.commondevelopmentframework.common.constant.ApiCodeConstant;
import com.nchu.commondevelopmentframework.common.domain.ApiResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @className: AuthAccessDeniedHandler
 * @description: 自定义用户权限不足的处理
 * @author: Li Chuanwei
 * @date: 2024/02/08 19:43
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Component
public class AuthAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws  IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String value = new ObjectMapper().writeValueAsString(ApiResult.fail(ApiCodeConstant.INSUFFICIENT_PERMISSIONS,"权限不足！"));
        response.getWriter().write(value);
    }
}
